using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Object_PlayerMissile : ObjectBulletBase
{
    [SerializeField] private float minBallisticAngle=-45;
    [SerializeField] private float maxBallisticAngle = 45;

    [Header("----- Explode Check Details-----")]
    [SerializeField] private float checkRadius = 1;
    [SerializeField] private LayerMask whatIsEnemy;
    private List<Transform> targetEnemyList = new();
    private bool isExplode = false;
    protected Coroutine coroutine;
    private void OnEnable()
    {
        isExplode = false;
    }
    private void Setup(Transform targetEnemy,float damage)
    {
        _damage = damage;
        coroutine ??= StartCoroutine(HomingCoroutine(targetEnemy));
    }
    protected override void OnTriggerEnter2D(Collider2D other)
    {
        if (isExplode)
            return;

        IDamagable damagable = other.GetComponent<IDamagable>();
        if (damagable == null)
            return;

        TriggerExplode();
    }
    
    private IEnumerator HomingCoroutine(Transform targetEnemy)
    {
        float randomEuler = Random.Range(minBallisticAngle, maxBallisticAngle);

        while (gameObject.activeSelf || Vector2.Distance(targetEnemy.position, transform.position) > .1f)
        {
            Vector2 targetDirection = targetEnemy.position - transform.position;
            transform.rotation = Quaternion.AngleAxis(Mathf.Atan2(targetDirection.y, targetDirection.x) * Mathf.Rad2Deg, Vector3.forward);
            transform.rotation *= Quaternion.Euler(0, 0, randomEuler);
            // transform.Translate(moveDir * moveSpeed * Time.deltaTime);
            yield return null;
        }

        if (isExplode == false)
            TriggerExplode();

        coroutine = null;
    } 
    private void TriggerExplode()
    {
        targetEnemyList.Clear();

        targetEnemyList = Physics2D.OverlapCircleAll(transform.position, checkRadius, whatIsEnemy).Select(t => t.transform).ToList();

        if (targetEnemyList.Count == 0 || targetEnemyList == null)
            return;

        foreach (var enemy in targetEnemyList)
        {
            IDamagable enemyDamagable = enemy.GetComponent<IDamagable>();
            if (enemyDamagable == null)
                continue;
            Vector2 hurtDir = (enemy.position - transform.position).normalized;
            enemyDamagable.TakeDamage(_damage, hurtDir);
        }

        isExplode = true;
    }
    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, checkRadius);
    }
}
